package main

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"github.com/lucheng0127/virtuallan/pkg/cli"
	"golang.org/x/net/websocket"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

func (a *App) shutdown(ctx context.Context) {
	// TODO: Send sigint to myself and the client will send FIN pkt to server
}

type SubmitParams struct {
	Target   string `json:"target"`
	Username string `json:"username"`
	Password string `json:"password"`
	Key      string `json:"key"`
	LogLevel string `json:"log_level"`
}

func (a *App) MirrorLog(ws *websocket.Conn) {
	r, w, err := os.Pipe()
	if err != nil {
		fmt.Println(err)
	}

	// Redirect stdout to pipe
	os.Stdout = w

	for {
		io.Copy(ws, r)
	}
}

func (a *App) CheckLogin() string {
	return "Login succeed"
}

// Submit returns a greeting for the given info
func (a *App) Submit(sp SubmitParams) {
	if err := cli.RunClient(
		cli.SetClientTarget(sp.Target),
		cli.SetClientUser(sp.Username),
		cli.SetClientPasswd(sp.Password),
		cli.SetClientKey(sp.Key),
		cli.SetClientLogLevel(sp.LogLevel),
	); err != nil {
		fmt.Println(err.Error())
	}

	for {
		time.Sleep(999999 * time.Hour)
	}
}
